﻿using HY.Common;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;

namespace HY.Web
{
    /// <summary>
    /// 自定义授权策略
    /// </summary>
    public class CustomAuthorizationHandler : AuthorizationHandler<IAuthorizationRequirement>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, IAuthorizationRequirement requirement)
        {
            if (!context.HasSucceeded) return Task.CompletedTask;//未登录

            HttpContext httpContext = context.Resource as HttpContext;
            string path = httpContext?.Request.Path ?? "/";//当前访问路径，例："/Home/Index"

            string roleId = httpContext.User.FindFirstValue(SystemConst.CookieKey.RoleId);
            string userName = httpContext.User.FindFirstValue(SystemConst.CookieKey.UserName);
            //已登录用户都有访问首页的权限
            if (path == "/" || roleId == "0")
            {
                context.Succeed(requirement);
                return Task.CompletedTask;
            }
            //httpContext.Request.RouteValues[""] 可以拿到area,controller,action的值
            if (!GlobalClass.AuthCheck(userName, roleId, path.TrimStart('/')))
                context.Fail();
            else 
                context.Succeed(requirement);
            //未设置context.Fail();或context.Succeed(requirement);则跳转登录页，设置context.Fail();跳转Program内的授权失败处理
            return Task.CompletedTask;
        }
    }
}
